import time

import bluetooth

# 定义目标设备名称和滑动指令
target_device_name = ["puamac的Redmi K70"]
swipe_up_command = bytearray(b"SWIPE_UP")  # 使用 bytearray
x_speed = 10  # 假设滑动速度为 10

# 修改滑动指令中的速度字段
# swipe_up_command[9] = x_speed  # 现在这是有效的

# 将 bytearray 转换回 bytes
swipe_up_command = "SWIPE_UP".encode('utf-8')  # 向上滑动，距离100，速度100



# 查找已连接的蓝牙设备
def find_bluetooth_devices():
    print("正在搜索已连接的蓝牙设备...")
    nearby_devices = bluetooth.discover_devices(duration=8, lookup_names=True)

    devices = []
    for addr, name in nearby_devices:
        print(f"设备名称: {name}, 设备地址: {addr}")
        if name in target_device_name:
            devices.append({"name": name, "address": addr})
    return devices


# 发送滑动指令到设备
def send_swipe_command(address):
    ports = [3]  # 尝试不同的端口，默认端口是1
    for port in ports:
        sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

        try:
            print(f"正在连接到设备 {address}...{port}...")
            sock.connect((address, port))
            print("连接成功")
            # 获取屏幕分辨率
            sock.send('GET_RESOLUTION')
            # 发送获取分辨率的命令
            response = sock.recv(1024)
            # 接收响应
            print(f"收到响应 SET_HISTOGRAM: {response}")

            # 发送滑动指令
            print("发送滑动指令...")
            # 模拟向上滑动屏幕
            # sock.send(swipe_up_command)

            print("向上滑动屏幕完成")
            # print(sock)
            # 接收响应（可选）
            # response = sock.recv(1024)
            # print(f"收到响应 {swipe_up_command}: {response}")
            # receive_data(sock)

        except bluetooth.btcommon.BluetoothError as err:
            print(f"连接失败: {err}")
        finally:
            sock.close()
            print("连接已关闭")




def receive_data(sock):
    while True:
        try:
            data = sock.recv(1024)
            if data:
                print(f"Received data: {data}")
                if b"SWIPE_RIGHT" in data:
                    swipe_right()
                elif b"SWIPE_LEFT" in data:
                    swipe_left()
        except bluetooth.btcommon.BluetoothError as err:
            print(f"Failed to receive data: {err}")
            break

def swipe_right():
    import pyautogui
    pyautogui.moveTo(100, 100)
    pyautogui.dragRel(300, 0, duration=0.5)

def swipe_left():
    import pyautogui
    pyautogui.moveTo(400, 100)
    pyautogui.dragRel(-300, 0, duration=0.5)

# https://zhuanlan.zhihu.com/p/638806553
# adb connect 192.168.1.104:40557
# adb shell input swipe 100 500 100 100

# 主函数
if __name__ == "__main__":
    devices = find_bluetooth_devices()
    for i in devices:
        name = i["name"]
        address = i["address"]
        print(f"滑动指令到设备: {name} - {address}")
        send_swipe_command(address)
